package org.codingq92.frame.springmvc;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.codingq92.frame.spring.ann.CusAutowired;
import org.codingq92.frame.spring.ann.CusComponent;
import org.codingq92.frame.spring.ann.CusPostConstruct;
import org.codingq92.frame.springmvc.core.CusDispatcherServlet;

import java.io.File;

@CusComponent
public class TomcatServer {

    private static final int PORT = 8080;

    @CusAutowired
    CusDispatcherServlet cusDispatcherServlet;

    /**
     * 启动Tomcat服务器
     * 该方法使用自定义注解@CusPostConstruct标记，在系统初始化时自动调用
     *
     * @throws LifecycleException 当Tomcat启动过程中发生生命周期异常时抛出
     */
    @CusPostConstruct
    public void startTomcat() throws LifecycleException {
        // 创建Tomcat实例并配置端口
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(PORT);
        tomcat.getConnector();

        // 配置应用上下文
        String contextPath = "";
        String doBase = new File(".").getAbsolutePath();
        Context context = tomcat.addContext(contextPath, doBase);

        // 添加自定义DispatcherServlet并映射到所有请求路径
        Tomcat.addServlet(context, "cusDispatcherServlet", cusDispatcherServlet);
        context.addServletMappingDecoded("/*", "cusDispatcherServlet");

        // 启动Tomcat服务器
        tomcat.start();
        System.out.println("Tomcat start on port " + PORT);
    }

}
